<template>
  <div class="profile-container">
    <!-- 顶部导航栏 -->
    <header class="profile-header">
      <button class="back-btn" @click="goBack">
        <span class="back-icon">‹</span>
        返回
      </button>
    </header>

    <!-- 个人信息区域 -->
    <main class="profile-main">
      <!-- 头像和姓名区域 -->
      <div class="profile-header-info">
        <h2 class="teacher-name" :class="{ 'loading-text': loading }">
          {{ loading ? '加载中...' : (teacherInfo?.realName || '教师') }}
        </h2>
        <div class="avatar-placeholder">
          <span class="avatar-text">{{ avatarInitial }}</span>
        </div>
      </div>
      
      <!-- 基本信息卡片 -->
      <div class="info-card">
        <!-- 修改按钮 -->
        <button class="card-edit-btn" @click="editBasicInfo">✏️</button>
        <!-- 基本信息 -->
        <div class="info-item readonly">
          <span class="info-label">工 号：</span>
          <span class="info-value" :class="{ 'loading-text': loading }">
            {{ loading ? '加载中...' : (teacherInfo?.workNumber || '暂无') }}
          </span>
        </div>
        <div class="info-item">
          <span class="info-label">手 机 号：</span>
          <span class="info-value" :class="{ 'loading-text': loading }">
            {{ loading ? '加载中...' : (teacherInfo?.phone || '暂无') }}
          </span>
        </div>
        <div class="info-item">
          <span class="info-label">邮 箱：</span>
          <span class="info-value" :class="{ 'loading-text': loading }">
            {{ loading ? '加载中...' : (teacherInfo?.email || '暂无') }}
          </span>
        </div>
        <div class="info-item">
          <span class="info-label">专业职位：</span>
          <span class="info-value" :class="{ 'loading-text': loading }">
            {{ loading ? '加载中...' : (teacherInfo?.position || '暂无') }}
          </span>
        </div>
        <div class="info-item">
          <span class="info-label">身份证号：</span>
          <span class="info-value" :class="{ 'loading-text': loading }">
            {{ loading ? '加载中...' : (teacherInfo?.idCard || '暂无') }}
          </span>
        </div>

      </div>

      <!-- 个人主页地址容器 -->
      <div class="homepage-card">
        <div class="info-item">
          <span class="info-label">个人主页地址：</span>
          <div class="homepage-content">
            <span class="homepage-url" :class="{ 'loading-text': loading }">
              {{ loading ? '加载中...' : (teacherInfo?.homepage || '暂未设置') }}
            </span>
            <button class="edit-btn" @click="editHomepage">✏️</button>
          </div>
        </div>
      </div>

      <!-- 功能按钮区 -->
      <div class="action-buttons">
        <button class="action-btn primary" @click="goToPersonalHomepage">个人主页</button>
        <button class="action-btn primary" @click="goToCreateTeam">组建队伍</button>
        <button class="action-btn primary" @click="goToSearchTeam">搜索队伍</button>
      </div>

      <!-- 指导队伍信息 -->
      <div class="section-card">
        <h3 class="section-title">指导队伍：</h3>
        <div v-if="teamsLoading" class="loading-container">
          <div class="loading-text">加载中...</div>
        </div>
        <div v-else-if="createdTeams.length > 0" class="team-buttons">
          <div 
            v-for="team in createdTeams" 
            :key="team.teamId"
            class="team-item-with-actions"
          >
            <button 
              class="team-btn"
              @click="goToTeamDetail(team)"
              :title="`队伍编号: ${team.teamCode}`"
            >
              {{ team.teamName }}
            </button>
          </div>
        </div>
        <div v-else class="empty-teams">
          <div class="empty-text">暂无指导队伍</div>
          <div class="empty-hint">可以点击"组建队伍"创建新的队伍</div>
        </div>
      </div>

      <!-- 入驻队伍信息 -->
      <div class="section-card">
        <h3 class="section-title">入驻队伍：</h3>
        <div v-if="teamsLoading" class="loading-container">
          <div class="loading-text">加载中...</div>
        </div>
        <div v-else-if="expertTeams.length > 0" class="team-buttons">
          <button 
            v-for="team in expertTeams" 
            :key="team.teamId"
            class="team-btn expert-btn"
            @click="goToTeamDetail(team)"
            :title="`队伍编号: ${team.teamCode}`"
          >
            {{ team.teamName }}
          </button>
        </div>
        <div v-else class="empty-teams">
          <div class="empty-text">暂无入驻队伍</div>
          <div class="empty-hint">可以点击"搜索队伍"寻找合适的队伍入驻</div>
        </div>
      </div>

      <!-- 获奖情况 -->
      <div class="section-card">
        <div class="section-header">
          <h3 class="section-title">获奖情况：</h3>
        </div>
        <AwardsManager />
      </div>

      <!-- 参赛经历 -->
      <div class="section-card">
        <div class="section-header">
          <h3 class="section-title">参赛经历：</h3>
        </div>
        <CompetitionsManager />
      </div>

      <!-- 项目经历 -->
      <div class="section-card">
        <div class="section-header">
          <h3 class="section-title">项目经历：</h3>
        </div>
        <ProjectsManager />
      </div>

      <!-- 底部按钮 -->
      <div class="bottom-actions">
        <button class="qr-btn" @click="generateQR" :disabled="qrLoading">
          {{ qrLoading ? '生成中...' : '生成页面二维码' }}
        </button>
        <button class="logout-btn" @click="handleLogout">退出登录</button>
      </div>
    </main>

    <!-- 退出登录确认弹窗 -->
    <div v-if="showLogoutModal" class="modal-overlay" @click="closeLogoutModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>确认退出</h3>
          <button class="close-btn" @click="closeLogoutModal">×</button>
        </div>
        <div class="modal-body">
          <div class="icon-wrapper">
            <div class="warning-icon">⚠️</div>
          </div>
          <p class="modal-text">确定要退出登录吗？</p>
          <p class="modal-subtitle">退出后需要重新登录才能使用系统</p>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeLogoutModal">取消</button>
          <button class="confirm-btn" @click="confirmLogout">确认退出</button>
        </div>
      </div>
    </div>

    <!-- 基本信息编辑弹窗 -->
    <div v-if="showBasicInfoModal" class="modal-overlay" @click="closeBasicInfoModal">
      <div class="modal-content edit-modal" @click.stop>
        <div class="modal-header">
          <h3>编辑基本信息</h3>
          <button class="close-btn" @click="closeBasicInfoModal">×</button>
        </div>
        <div class="modal-body">
          <form class="edit-form">
            <div class="form-group">
              <label>手机号：</label>
              <input 
                v-model="basicInfoForm.phone" 
                type="tel" 
                class="form-input"
                placeholder="请输入手机号"
                maxlength="11"
              />
            </div>
            <div class="form-group">
              <label>邮箱：</label>
              <input 
                v-model="basicInfoForm.email" 
                type="email" 
                class="form-input"
                placeholder="请输入邮箱地址"
              />
            </div>
            <div class="form-group">
              <label>专业职位：</label>
              <input 
                v-model="basicInfoForm.professionalTitle" 
                type="text" 
                class="form-input"
                placeholder="请输入专业职位"
              />
            </div>
            <div class="form-group">
              <label>身份证号：</label>
              <input 
                v-model="basicInfoForm.idCard" 
                type="text" 
                class="form-input"
                placeholder="请输入身份证号"
                maxlength="18"
              />
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeBasicInfoModal" :disabled="basicInfoLoading">取消</button>
          <button class="confirm-btn" @click="saveBasicInfo" :disabled="basicInfoLoading">
            {{ basicInfoLoading ? '保存中...' : '保存' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 个人主页编辑弹窗 -->
    <div v-if="showHomepageModal" class="modal-overlay" @click="closeHomepageModal">
      <div class="modal-content edit-modal" @click.stop>
        <div class="modal-header">
          <h3>编辑个人主页</h3>
          <button class="close-btn" @click="closeHomepageModal">×</button>
        </div>
        <div class="modal-body">
          <form class="edit-form">
            <div class="form-group">
              <label>个人主页地址：</label>
              <input 
                v-model="homepageForm.personalHomepage" 
                type="url" 
                class="form-input"
                placeholder="请输入个人主页地址，如：https://www.example.com"
              />
              <div class="form-hint">
                填写后可点击"个人主页"按钮快速访问
              </div>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeHomepageModal" :disabled="homepageLoading">取消</button>
          <button class="confirm-btn" @click="saveHomepage" :disabled="homepageLoading">
            {{ homepageLoading ? '保存中...' : '保存' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 二维码显示弹窗 -->
    <div v-if="showQRModal" class="modal-overlay" @click="closeQRModal">
      <div class="modal-content qr-modal" @click.stop>
        <div class="modal-header">
          <h3>个人详情页面二维码</h3>
          <button class="close-btn" @click="closeQRModal">×</button>
        </div>
        <div class="modal-body">
          <div class="qr-container">
            <img :src="qrCodeDataURL" alt="个人详情页面二维码" class="qr-image" />
            <div class="qr-description">
              <p class="qr-title">{{ teacherInfo?.realName }}的个人详情页面</p>
              <p class="qr-subtitle">扫描二维码查看详细信息</p>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="download-btn" @click="downloadQR">下载二维码</button>
          <button class="confirm-btn" @click="closeQRModal">关闭</button>
        </div>
      </div>
    </div>

    <!-- 消息提示弹窗 -->
    <div v-if="showMessageModal" class="modal-overlay" @click="closeMessageModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header" :class="messageType === 'success' ? 'success-header' : 'error-header'">
          <h3>{{ messageTitle }}</h3>
          <button class="close-btn" @click="closeMessageModal">×</button>
        </div>
        <div class="modal-body">
          <div class="icon-wrapper">
            <div class="message-icon" :class="messageType === 'success' ? 'success-icon' : 'error-icon'">
              {{ messageType === 'success' ? '✓' : '✗' }}
            </div>
          </div>
          <p class="modal-text">{{ messageText }}</p>
        </div>
        <div class="modal-footer">
          <button class="confirm-btn" @click="closeMessageModal">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useTeacherStore } from '@/stores/teacher.js'
import { useTokenStore } from '@/stores/token.js'
import { getTeacherInfoService, updateBasicInfoService, updatePersonalHomepageService } from '@/api/teacher.js'
import { getMyTeamsService } from '@/api/team.js'
import AwardsManager from '@/components/AwardsManager.vue'
import CompetitionsManager from '@/components/CompetitionsManager.vue'
import ProjectsManager from '@/components/ProjectsManager.vue'
// 注意：需要先安装qrcode库：npm install qrcode
import QRCode from 'qrcode'

const router = useRouter()
const teacherStore = useTeacherStore()
const tokenStore = useTokenStore()

// 退出登录弹窗控制
const showLogoutModal = ref(false)
// 数据加载状态
const loading = ref(false)

// 基本信息编辑弹窗控制
const showBasicInfoModal = ref(false)
const basicInfoForm = ref({
  phone: '',
  email: '',
  professionalTitle: '',
  idCard: ''
})
const basicInfoLoading = ref(false)

// 个人主页编辑弹窗控制
const showHomepageModal = ref(false)
const homepageForm = ref({
  personalHomepage: ''
})
const homepageLoading = ref(false)

// 消息提示弹窗控制
const showMessageModal = ref(false)
const messageTitle = ref('')
const messageText = ref('')
const messageType = ref('success') // success | error

// 二维码弹窗控制
const showQRModal = ref(false)
const qrCodeDataURL = ref('')
const qrLoading = ref(false)

// 教师队伍信息
const teacherTeams = ref(null)
const createdTeams = ref([])
const expertTeams = ref([])
const teamsLoading = ref(false)

// 获取教师信息
const teacherInfo = computed(() => teacherStore.teacherInfo)

// 头像首字母
const avatarInitial = computed(() => {
  if (loading.value) return '...'
  const name = teacherInfo.value?.realName || '教师'
  return name.charAt(0)
})

// 页面挂载时获取教师信息
onMounted(async () => {
  // 检查登录状态
  if (!tokenStore.token) {
    router.push('/login')
    return
  }
  
  // 总是从服务器获取最新的教师信息
  await fetchTeacherInfo()
  // 获取教师队伍信息
  await fetchTeacherTeams()
})

// 刷新队伍信息（可以在返回页面时调用）
const refreshTeamInfo = async () => {
  await fetchTeacherTeams()
}

// 监听路由变化，当从其他页面返回时刷新队伍信息
router.afterEach((to, from) => {
  if (to.name === 'Profile' && from.name === 'TeamDetail') {
    // 从队伍详情页面返回时，刷新队伍信息
    setTimeout(() => {
      refreshTeamInfo()
    }, 100)
  }
})

// 获取教师队伍信息
const fetchTeacherTeams = async () => {
  teamsLoading.value = true
  try {
    const result = await getMyTeamsService()
    if (result.code === 200) {
      teacherTeams.value = result.data
      createdTeams.value = result.data.createdTeams || []
      expertTeams.value = result.data.expertTeams || []
      console.log('教师队伍信息获取成功:', result.data)
    } else {
      console.error('获取教师队伍信息失败:', result.msg)
      showErrorMessage(result.msg || '获取队伍信息失败')
    }
  } catch (error) {
    console.error('获取教师队伍信息异常:', error)
    showErrorMessage('获取队伍信息时发生错误')
  } finally {
    teamsLoading.value = false
  }
}

// 获取教师信息
const fetchTeacherInfo = async () => {
  loading.value = true
  try {
    const result = await getTeacherInfoService()
    if (result.code === 200) {
      // 创建教师数据对象，明确设置每个字段
      const originalData = result.data
      const teacherData = {
        // 基本信息
        id: originalData.id,
        employeeId: originalData.employeeId,
        username: originalData.username,
        realName: originalData.realName,
        phone: originalData.phone,
        email: originalData.email,
        idCard: originalData.idCard,
        professionalTitle: originalData.professionalTitle,
        personalHomepage: originalData.personalHomepage,
        auditStatus: originalData.auditStatus,
        status: originalData.status,
        createTime: originalData.createTime,
        updateTime: originalData.updateTime,
        // 映射字段
        workNumber: originalData.employeeId,  // 工号
        position: originalData.professionalTitle,  // 专业职位
        homepage: originalData.personalHomepage  // 个人主页
      }

      teacherStore.setTeacherInfo(teacherData)
    } else {
      console.error('获取教师信息失败:', result.msg)
    }
  } catch (error) {
    console.error('获取教师信息异常:', error)
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 编辑基本信息
const editBasicInfo = () => {
  // 预填充当前数据
  basicInfoForm.value = {
    phone: teacherInfo.value?.phone || '',
    email: teacherInfo.value?.email || '',
    professionalTitle: teacherInfo.value?.professionalTitle || '',
    idCard: teacherInfo.value?.idCard || ''
  }
  showBasicInfoModal.value = true
}

// 关闭基本信息编辑弹窗
const closeBasicInfoModal = () => {
  showBasicInfoModal.value = false
  basicInfoForm.value = {
    phone: '',
    email: '',
    professionalTitle: '',
    idCard: ''
  }
}

// 保存基本信息
const saveBasicInfo = async () => {
  basicInfoLoading.value = true
  try {
    const result = await updateBasicInfoService(basicInfoForm.value)
    if (result.code === 200) {
      // 更新成功，刷新教师信息
      await fetchTeacherInfo()
      closeBasicInfoModal()
      showSuccessMessage('基本信息更新成功')
    } else {
      // 显示后端返回的具体错误信息
      showErrorMessage(result.msg || '基本信息更新失败')
    }
  } catch (error) {
    console.error('更新基本信息异常:', error)
    console.log('错误对象结构:', JSON.stringify(error, null, 2))
    
    // 检查错误对象中是否包含后端返回的错误信息
    let errorMessage = '更新基本信息时发生错误，请稍后重试'
    
    // 优先检查直接的错误对象格式（如您提供的日志格式）
    if (error && error.code && error.msg) {
      console.log('使用直接错误格式:', error.msg)
      errorMessage = error.msg
    } else if (error && error.response && error.response.data) {
      // axios错误响应格式
      const responseData = error.response.data
      if (responseData.msg) {
        console.log('使用axios响应错误格式:', responseData.msg)
        errorMessage = responseData.msg
      } else if (responseData.message) {
        console.log('使用axios响应message格式:', responseData.message)
        errorMessage = responseData.message
      }
    } else if (error && error.msg) {
      // 其他直接错误格式
      console.log('使用其他msg格式:', error.msg)
      errorMessage = error.msg
    } else if (error && error.message) {
      // 标准JavaScript错误格式
      console.log('使用标准message格式:', error.message)
      errorMessage = error.message
    }
    
    console.log('最终错误消息:', errorMessage)
    showErrorMessage(errorMessage)
  } finally {
    basicInfoLoading.value = false
  }
}

// 编辑个人主页
const editHomepage = () => {
  // 预填充当前数据
  homepageForm.value = {
    personalHomepage: teacherInfo.value?.personalHomepage || ''
  }
  showHomepageModal.value = true
}

// 关闭个人主页编辑弹窗
const closeHomepageModal = () => {
  showHomepageModal.value = false
  homepageForm.value = {
    personalHomepage: ''
  }
}

// 保存个人主页
const saveHomepage = async () => {
  homepageLoading.value = true
  try {
    const result = await updatePersonalHomepageService(homepageForm.value)
    if (result.code === 200) {
      // 更新成功，刷新教师信息
      await fetchTeacherInfo()
      closeHomepageModal()
      showSuccessMessage('个人主页更新成功')
    } else {
      // 显示后端返回的具体错误信息
      showErrorMessage(result.msg || '个人主页更新失败')
    }
  } catch (error) {
    console.error('更新个人主页异常:', error)
    console.log('错误对象结构:', JSON.stringify(error, null, 2))
    
    // 检查错误对象中是否包含后端返回的错误信息
    let errorMessage = '更新个人主页时发生错误，请稍后重试'
    
    // 优先检查直接的错误对象格式（如您提供的日志格式）
    if (error && error.code && error.msg) {
      console.log('使用直接错误格式:', error.msg)
      errorMessage = error.msg
    } else if (error && error.response && error.response.data) {
      // axios错误响应格式
      const responseData = error.response.data
      if (responseData.msg) {
        console.log('使用axios响应错误格式:', responseData.msg)
        errorMessage = responseData.msg
      } else if (responseData.message) {
        console.log('使用axios响应message格式:', responseData.message)
        errorMessage = responseData.message
      }
    } else if (error && error.msg) {
      // 其他直接错误格式
      console.log('使用其他msg格式:', error.msg)
      errorMessage = error.msg
    } else if (error && error.message) {
      // 标准JavaScript错误格式
      console.log('使用标准message格式:', error.message)
      errorMessage = error.message
    }
    
    console.log('最终错误消息:', errorMessage)
    showErrorMessage(errorMessage)
  } finally {
    homepageLoading.value = false
  }
}






// 生成二维码
const generateQR = async () => {
  if (!teacherInfo.value?.employeeId) {
    showErrorMessage('获取用户信息失败，无法生成二维码')
    return
  }

  qrLoading.value = true
  try {
    // 生成教师详情页面的完整URL
    const baseUrl = window.location.origin
    const teacherDetailUrl = `${baseUrl}/teacher-detail/${teacherInfo.value.employeeId}`
    
    console.log('生成二维码，URL:', teacherDetailUrl)
    
    // 生成二维码
    const qrDataURL = await QRCode.toDataURL(teacherDetailUrl, {
      width: 300,
      margin: 2,
      color: {
        dark: '#000000',
        light: '#FFFFFF'
      }
    })
    
    qrCodeDataURL.value = qrDataURL
    showQRModal.value = true
  } catch (error) {
    console.error('生成二维码失败:', error)
    showErrorMessage('生成二维码失败，请稍后重试')
  } finally {
    qrLoading.value = false
  }
}

// 退出登录 - 显示确认弹窗
const handleLogout = () => {
  showLogoutModal.value = true
}

// 关闭退出登录弹窗
const closeLogoutModal = () => {
  showLogoutModal.value = false
}

// 确认退出登录
const confirmLogout = () => {
  tokenStore.removeToken()
  teacherStore.clearTeacherInfo()
  showLogoutModal.value = false
  router.push('/login')
}

// 显示成功消息
const showSuccessMessage = (text) => {
  messageTitle.value = '操作成功'
  messageText.value = text
  messageType.value = 'success'
  showMessageModal.value = true
}

// 显示错误消息
const showErrorMessage = (text) => {
  messageTitle.value = '操作失败'
  messageText.value = text
  messageType.value = 'error'
  showMessageModal.value = true
}

// 关闭消息弹窗
const closeMessageModal = () => {
  showMessageModal.value = false
}

// 关闭二维码弹窗
const closeQRModal = () => {
  showQRModal.value = false
  qrCodeDataURL.value = ''
}

// 下载二维码
const downloadQR = () => {
  if (!qrCodeDataURL.value) return
  
  const link = document.createElement('a')
  link.download = `${teacherInfo.value?.realName || '教师'}_个人详情二维码.png`
  link.href = qrCodeDataURL.value
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 个人主页跳转
const goToPersonalHomepage = () => {
  const homepage = teacherInfo.value?.homepage || teacherInfo.value?.personalHomepage
  if (homepage) {
    // 如果地址不包含协议，自动添加https://
    const url = homepage.startsWith('http') ? homepage : `https://${homepage}`
    window.open(url, '_blank')
  } else {
    showErrorMessage('请先设置个人主页地址')
  }
}

// 跳转到组建队伍页面
const goToCreateTeam = () => {
  router.push('/create-team')
}

// 跳转到搜索队伍页面
const goToSearchTeam = () => {
  router.push('/search-team')
}

// 跳转到队伍详情页面
const goToTeamDetail = (team) => {
  // 判断用户在队伍中的角色
  const userRole = createdTeams.value.some(t => t.teamId === team.teamId) ? 'instructor' : 'expert'
  
  router.push({
    name: 'TeamDetail',
    params: { teamId: team.teamId },
    query: { role: userRole } // 传递角色信息
  })
}

// 管理队伍成员
const manageTeam = (team) => {
  router.push({
    name: 'CreateTeam',
    params: { teamId: team.teamId },
    query: { mode: 'edit' }
  })
}
</script>

<style scoped lang="scss">
@import '@/assets/css/profile.css';
</style> 